/*
@auther fenglei
*/
package xxhttp

import (
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/panjf2000/ants/v2"
	"sync"
)

type AntsParam struct {
	Url  string
	Data interface{}
	//透传值
	Unvarnished interface{}
}

// ReqMessage 返回
type AntsReqMessage struct {
	Code int
	Body string
	Err  error
	Url  string
	//透传值
	Unvarnished interface{}
}

func (e *OpsHttpClient) AntsHttp(params []*AntsParam, PoolNum int) *garray.Array {
	list := garray.NewArray(true)
	defer ants.Release()
	var wg sync.WaitGroup
	options := ants.Options{}
	options.PreAlloc = true
	//控制池线程大小
	limit := len(params)
	if PoolNum > 0 {
		limit = PoolNum
	}
	p, _ := ants.NewPoolWithFunc(limit, func(i interface{}) {
		list.Append(e.req(i))
		wg.Done()
	}, ants.WithOptions(options))
	defer p.Release()
	for _, v := range params {
		wg.Add(1)
		_ = p.Invoke(v)
	}
	wg.Wait()
	return list
}
func (e *OpsHttpClient) req(i interface{}) *AntsReqMessage {
	mes := new(AntsReqMessage)
	if !g.IsNil(i) {
		obj := i.(*AntsParam)
		message := e.HttpRequest(obj.Url, obj.Data)
		mes.Code = message.Code
		mes.Err = message.Err
		mes.Body = message.Body
		mes.Url = obj.Url
		mes.Unvarnished = obj.Unvarnished
	}
	return mes
}
